package com.vitogiovanni.tobook.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;
import com.vitogiovanni.tobook.entity.Foto;
import com.vitogiovanni.tobook.entity.LocaleEndpoint;

public class InserisciAvatarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public InserisciAvatarServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	// private BlobstoreService blobstoreService =
	// BlobstoreServiceFactory.getBlobstoreService();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		LocaleEndpoint localeEndpoint = new LocaleEndpoint();

		// FotoEndpoint fotoEndpoint = new FotoEndpoint();
		// Foto foto = null;

		String localeId = "";
		Blob imageBlob = null;
		try {
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = upload.getItemIterator(req);

			while (iter.hasNext()) {
				FileItemStream item = iter.next();
				InputStream stream = item.openStream();

				// Elaboro i campi che non sono file
				if (item.isFormField()) {
					if (item.getFieldName().equals("localeId")) {
						localeId = Streams.asString(stream);
					}
				} else {// Elaboro gli eventuali file presenti
					imageBlob = new Blob(IOUtils.toByteArray(stream));
				}
			}
		} catch (FileUploadException e) {
			throw new ServletException("Cannot parse multipart request.", e);
		}

		localeEndpoint.insertAvatar(new Foto(imageBlob), localeId);
		// fotoEndpoint.insertFoto(foto);

		resp.sendRedirect("/inserimento.html");
	}
}
